package com.timous.others;

/**
 * https://leetcode-cn.com/problems/add-two-numbers/
 * @author Timous
 * @create 2020-12-27 18:33
 **/
public class _2_两数相加 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = new ListNode();
        ListNode rest = res;
        int flag = 0;
        int s ;
        while (l1 != null || l2 != null){
            if (l1 == null){
                s = l2.val + flag;
                if (s >= 10){
                    flag = 1;
                }else {
                    flag = 0;
                }
                l2 = l2.next;
            }else if (l2 == null){
                s = l1.val + flag;
                if (s >= 10){
                    flag = 1;
                }else {
                    flag = 0;
                }
                l1 = l1.next;
            }else{
                s = l1.val + l2.val;
                s = s + flag;
                if (s >= 10){
                    flag = 1;
                }else {
                    flag = 0;
                }
                l1 = l1.next;
                l2 = l2.next;
            }
            s = s % 10;
            rest.next = new ListNode(s , null);
            rest = rest.next;
        }
        //处理之后的情况 ， 如果flag（发生进位 ， 需要再增加一位）
        if (flag == 1){
            rest.next = new ListNode(1 , null);
        }
        return res.next;
    }
}
